package zmq

import (
	"encoding/json"
	"fmt"
	"usplatformserver/global"
	"usplatformserver/internal/model"

	zmq "github.com/pebbe/zmq4"
)

func Subscriber(ip string, port uint32) (*zmq.Context, *zmq.Socket) {
	context, _ := zmq.NewContext()
	subscriber, _ := context.NewSocket(zmq.SUB)
	subscriber.SetRcvhwm(5 * 1000)
	subscriber.SetSubscribe("")
	err := subscriber.Connect(fmt.Sprintf("tcp://%s:%d", ip, port))
	if nil != err {
		global.Logger.Infof("subscriber connect failed: %v", err)
	}

	return context, subscriber
}

func Listener(sub *zmq.Socket) {
	for {
		s, err := sub.Recv(0)
		if err != nil {
			global.Logger.Infof("subscriber receive failed: %v", err)
			continue
		}

		var bn *model.BaseNotify
		err = json.Unmarshal([]byte(s), &bn)
		if err != nil {
			fmt.Println("json.Unmarshal(BaseNotify) failed: ", err)
			return
		}
		//fmt.Printf("notify code: %v", bn.Code)
		if bn.Code != MsgZmqPubKeepAlive.MsgType {
			// 分发消息类型
			global.MqttClient.NotifyMessage(s)
		}
	}
}
